<template>
	<!-- 公海 -->
	<div class="app-container">
		<!-- 使用搜索组件 -->
		<searchOption id="searchForm" ref="searchUnit" type="public" :total="total" :status="queryParams.status"
			@searchList="parentSearchList" @getSelectEvent="getSelectEvent">
		</searchOption>

		<!-- 表格 -->
		<vxe-table border ref="xTable" show-overflow :data="infoList" :column-config="{ resizable: false }"
			:cell-style="cellStyle" :row-style="rowStyle" :menu-config="tableMenu" @menu-click="contextMenuClickEvent"
			:edit-config="{ trigger: 'click', mode: 'cell' }" :height="autoTableHeight" size="mini" @scroll="srcollFn">
			<vxe-column type="checkbox" width="40" v-if="queryParams.status == 5 || queryParams.status == 6"></vxe-column>
			<vxe-column field="seaTime" title="申请时间" :edit-render="{}" width="125">
				<template #edit="{ row }">
					<vxe-input v-model="row.seaTime" type="datetime" placeholder="请选择日期" width="125" transfer
						@change="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>
			<vxe-column field="sendDataTime" title="发送时间" width="125">
				<template #default="{ row }">
					{{ row.sendDataTime }}
				</template>
			</vxe-column>

			<vxe-column field="customManager" title="销售经理" :edit-render="{}" width="80"
				v-if="$store.state.user.roles.includes('topManager')">
				<template #edit="{ row }">
					<vxe-input v-model="row.customManager" type="text" placeholder="请输入销售经理" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="applyName" title="申请人" width="100" :visible="queryParams.status == 6"> </vxe-column>

			<vxe-column field="source" title="渠道" width="100" :edit-render="{}">
				<template #edit="{ row }">
					<vxe-input v-model="row.source" type="text" placeholder="输入渠道" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="degree" title="状态" width="70" :edit-render="{}" :visible="queryParams.status == 5">
				<template #default="{ row }">
					<span>{{ formatDegree(row.degree) }}</span>
				</template>
				<template #edit="{ row }">
					<vxe-select v-model="row.degree" transfer @change="nameChangeEvent({ row })">
						<vxe-option v-for="item in degreeList" :key="item.value" :value="item.value" :label="item.label">
						</vxe-option>
					</vxe-select>
				</template>
			</vxe-column>

			<vxe-column field="introducer" title="介绍人" width="90" :edit-render="{}">
				<template #edit="{ row }">
					<vxe-select v-model="row.introducer" filterable placeholder="请选择介绍人" :filter-method="getIntroducerOptionsFc()"
						@change="nameChangeEvent({ row })">
						<vxe-option v-for="item in introducerOptions" :key="item" :label="item" :value="item">
						</vxe-option>
					</vxe-select>
				</template>
			</vxe-column>

			<vxe-column field="callName" width="70" title="姓名" :edit-render="{}">
				<template #edit="{ row }">
					<vxe-input v-model="row.callName" type="text" placeholder="输入姓名" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="callPhone" title="电话号" width="100" :edit-render="{}">
				<template #edit="{ row }">
					<vxe-input v-model="row.callPhone" type="text" placeholder="输入电话"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="quotation" title="报价金额" width="80" :edit-render="{}">
				<template #edit="{ row }">
					<vxe-input v-model="row.quotation" type="text" placeholder="报价金额"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="lastRemark" title="上次回访">
				<template #default="{ row }">
					{{ row.lastRemark }}
				</template>
			</vxe-column>

			<vxe-column title="操作" width="80" :visible="queryParams.status == 2">
				<template #default="{ row }">
					<el-dropdown @command="handleCommand($event, row)">
						<span class="el-dropdown-link">
							操作选项<i class="el-icon-arrow-down el-icon--right"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="1">历史回访</el-dropdown-item>
							<el-dropdown-item divided command="2">申请</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</template>
			</vxe-column>

		</vxe-table>
		<!-- 回访记录 -->
		<el-dialog title="回访记录" :visible.sync="openRecord" width="70%" append-to-body>
			<el-table v-loading="loading" :data="remarkList" @selection-change="handleSelectionChange">
				<el-table-column label="回访记录" align="center" prop="remark" />
				<el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.gmtCreate, "{y}-{m}-{d}") }}</span>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script>
import {
	listInfo,
	getInfo,
	delInfo,
	addInfo,
	applyBecome,
	updateInfo,
	findCustom,
	listContract,
	applyAddPublicApprove
} from "@/api/system/info";
import { listUser } from "@/api/system/user";
import searchOption from "@/components/searchOption";

import { updateRemark, addRemark, listRemark } from "@/api/system/remark";
import { addDetail } from "@/api/system/detail";
import { number } from "echarts";
export default {
	name: "Info",
	components: {
		searchOption
	},
	dicts: ["status_custom"],
	data() {
		return {
			requeryFlag: true,
			remarkId: "",
			autoTableHeight: 750,
			formRemark: {},
			openRecord: false,
			openContract: false,
			remarkList: [],
			// 右键菜单
			tableMenu: {},
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 客户信息表格数据
			infoList: [],
			// 弹出层标题
			title: "",
			callPhone: "",
			introducerOptions: [],
			// 申请进入公海列表的 状态
			degreeList: [
				{
					label: "待跟进",
					value: "0",
				},
				{
					label: "高意向",
					value: "1",
				},
				{
					label: "无效",
					value: "2",
				},
			],
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 30,
				customName: null,
				source: null,
				callPhone: null,
				callName: null,
				customManager: null,
				status: 2,
			},
			// 表单参数
			form: {
				groupDate: [],
			},
			// 表单校验
			customManagerOptions: [],
		};
	},
	created() {
		this.getCustomManagerFc("");
		this.getIntroducerOptionsFc("");
	},
	watch: {
		// 监听路由对象中的变化
		'$route': {
			handler: function (from, to) {
				// 当路由发生变化时会调用这个函数
				this.infoList = [];
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 30;
				this.queryParams.customName = null;
				this.queryParams.callPhone = null;
				this.queryParams.callName = null;
				this.queryParams.customManager = null;
				this.queryParams.source = null;
				this.tableMenu = {};
				this.queryParams.status = from.query.status;
				if (from.query.isDelete) {
					this.isDelete = true;
				} else {
					this.isDelete = false;
				}
				// 只有客户列表有右键菜单
				if (from.query.status == '2' && !from.query.isDelete) {
					this.tableMenu = {
						body: {
							options: [
								[
									{ code: "insertAt", name: "插入", disabled: false },
									{ code: "remove", name: "删除", disabled: false },
								],
							],
						},
						visibleMethod: this.visibleMethod,
					}
				} else if (from.query.status == '5' || from.query.status == '6' && !from.query.isDelete) {
					this.tableMenu = {
						body: {
							options: [
								[
									{
										code: "insertAt",
										name: "插入",
										disabled: false,
									},
									{
										code: "remove",
										name: "删除",
										disabled: false,
									},
									{
										code: "keyIs",
										name: "红色",
										disabled: false,
									},
									{
										code: "cancelKeyIs",
										name: "黄色",
										disabled: false,
									},
									{
										code: "cancel",
										name: "取消",
										disabled: false,
									},
								],
							],
						},
					}
				}
				this.getList();
			},
			// 如果需要在路由变化时立即响应，可以设置immediate为true
			immediate: true
		}
	},
	mounted() {
		// 计算表格高度   视口高度 - 列表上方的元素高度
		// tags-view-container   searchForm    navbar
		// 视口高度 - 列表上方的元素高度
		let allHeight = window.innerHeight;
		let element = [
			document.getElementById('navbar'),
			document.getElementById('searchForm'),
			document.getElementById('tags-view-container'),
		]
		let domHeight = element.map(item => item.offsetHeight)
		// let tableHeight = allHeight - 50 - 34 - 50 - 36;
		let tableHeight = allHeight - 40 - domHeight[0] - domHeight[1] - domHeight[2];
		this.autoTableHeight = tableHeight;
	},
	methods: {
		// 搜索子组件触发搜索
		parentSearchList(data) {
			this.queryParams.pageNum = data.pageNum;
			this.queryParams.pageSize = data.pageSize;
			this.queryParams.callName = data.callName;
			this.queryParams.callPhone = data.callPhone;
			this.queryParams.customName = data.customName;
			this.queryParams.customManager = data.customManager;
			this.handleQuery();
		},
		// 状态
		formatDegree(value) {
			if (value == "0") {
				return "待跟进";
			}
			if (value == "1") {
				return "高意向";
			}
			if (value == "2") {
				return "无效";
			}
			return "";
		},
		// 右键菜单响应
		contextMenuClickEvent({ menu, row, column }) {
			let xTable = this.$refs.xTable;
			switch (menu.code) {
				case "insertAt":
					this.insertEvent(row);
					break;
				case "remove":
					xTable.remove(row);
					this.delInfo(row);
					break;
				case "keyIs":
					this.keyIsFc(row, column, 1);
					break;
				case "cancelKeyIs":
					this.keyIsFc(row, column, 2);
					break;
				case "cancel":
					this.keyIsFc(row, column, 0);
					break;
			}
		},
		// 删除数据
		delInfo(row) {
			delInfo(row.id).then((response) => {
				this.getList();
			});
		},
		// 插入数据
		async insertEvent(row) {
			const records = [];
			for (let i = 0; i < 1; i++) {
				const record = {
					callPhone: ``,
					callName: ``,
					customManager: this.$store.state.user.name || "",
					degree: 0,
					status: this.queryParams.status,
					source: ``,
					lastRemark: ``,
				};
				records.push(record);
			}
			await addInfo(records);
			this.getList();
			this.$refs.xTable.clearScroll();
		},
		//关键客户
		keyIsFc(row, column, num) {
			let form = row;
			form.keyIs = num;
			updateInfo(form).then((response) => {
				this.getList();
			});
		},
		// 行背景
		rowStyle({ row }) {
			return {
				backgroundColor: this.queryParams.status == '2' ? "#EAC8FB" : "#9EDBF7",
			};
		},
		// 单元格背景
		cellStyle({ row, column }) {
			if (column.field === "callName") {
				if (row.keyIs == 3) {
					return {
						backgroundColor: "#FF9192 !important",
					};
				}

				if (row.keyIs == 5) {
					return {
						backgroundColor: "#FEE765 !important",
					};
				}
			}
		},
		/** 查询客户信息列表 */
		getList() {
			this.loading = true;
			listInfo(this.queryParams).then((response) => {
				this.infoList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		nameChangeEvent({ row }) {
			let form = row;
			// console.log(form.status)
			updateInfo(form).then((response) => {
				// this.getList();
			});
		},

		/**
		 *
		 * @param {*} row
		 * 操作菜单
		 */
		handleCommand(e, row) {
			if (e === '1') {
				// 历史回访
				this.talkBackHistory(row)
			} else {
				// 申请
				this.handleUpdate(row.id)
			}
		},
		//  历史回访
		talkBackHistory(row) {
			this.openRecord = true;
			let customId = row.id;
			let queryParams = {
				pageNum: 1,
				pageSize: 30,
			};
			if (customId) {
				queryParams.customId = customId;
			}
			console.log("customId", customId);
			listRemark(queryParams).then((response) => {
				this.remarkList = response.rows;
			});
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 修改按钮操作 */
		handleUpdate(applyId) {
			// console.log("添加回访", row);
			// this.formRemark = {};
			console.log(applyId);
			// this.remarkId = row.id;
			applyBecome(applyId).then((response) => {
				// 刷新列表
				this.getList();
			});
		},

		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"custom/info/export",
				{
					...this.queryParams,
				},
				`info_${new Date().getTime()}.xlsx`
			);
		},

		//获取客户经理下拉
		getCustomManagerFc(e) {
			if (e !== undefined) {
				listUser(e).then((response) => {
					this.customManagerOptions = response.rows;
				});
			}
		},
		// 滚动加载
		srcollFn(e) {
			let circulateNum = this.total / 30;
			let bottomOffset = e.scrollHeight - e.scrollTop - e.bodyHeight;
			if (bottomOffset < 50 && this.queryParams.pageNum < circulateNum) {
				if (this.requeryFlag) {
					this.requeryFlag = false;
					this.loading = true;
					this.queryParams.pageNum++;
					const h = this.$createElement;
					listInfo(this.queryParams).then((response) => {
						this.infoList = [...this.infoList, ...response.rows];
						// this.total = response.total;
						this.loading = false;
						this.requeryFlag = true;
					});
				}
			}
		},
		// 申请进入公海列表  申请公海客户列表的同意和拒绝
		/**
		 *
		 * @param {*} statusApprove
		 * 申请进入公海列表 status：5 同意：2，拒绝：0
		 * 申请公海客户列表 status：6 同意：7，拒绝：5
		 */
		getSelectEvent(data) {
			console.log(data);
			let selectRecords = this.$refs.xTable.getCheckboxRecords();
			//循环selectRecords并取出ID
			let ids = [];
			selectRecords.forEach((item) => {
				ids.push(item.id);
			});
			if (ids.length == 0) {
				this.$modal.msgError("请选择需要操作的数据！");
				return
			}
			let msg;
			let statusApprove = null;
			if (data && (this.queryParams.status == 5 || this.queryParams.status == 6)) {
				msg = "同意";
				statusApprove = this.queryParams.status == 5 ? 2 : this.queryParams.status == 6 ? 7 : null;
			} else {
				msg = "拒绝";
				if (this.queryParams.status == 5 || this.queryParams.status == 6) {
					statusApprove = this.queryParams.status == 5 ? 0 : this.queryParams.status == 6 ? 5 : null;
				}
			}
			let idsString = ids.join(",");
			console.log(idsString);
			this.$modal
				.confirm('是否确认"' + msg + '"客户信息编号为"' + ids + '"的数据项？')
				.then(() => {
					// 调用删除信息的函数，并返回 Promise
					return applyAddPublicApprove(idsString, statusApprove);
				})
				.then(() => {
					// 刷新列表
					this.getList();
					// 显示成功消息
					this.$modal.msgSuccess("操作成功！");
				})
				.catch(() => {
					// 处理错误情况，比如可以显示一个错误消息
					this.$modal.msgError("操作失败！");
				});
		},
		//获取介绍人下拉
		getIntroducerOptionsFc(e) {
			if (e !== undefined) {
				findCustom(e).then((response) => {
					this.introducerOptions = response.rows;
				});
			}
		},
	}
};
</script>
<style>
.el-row {
	margin-bottom: 20px;
}
</style>